/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.ChangeDelta;
import com.velocityme.entity.Organisation;
import com.velocityme.enums.ChangeDeltaType;
import com.velocityme.enums.Permission;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class OrganisationBean implements OrganisationLocal {
    @EJB
    private ContactableLocal contactableBean;

    @PersistenceContext
    private EntityManager em;

    public Organisation findOrganisation(KeyLocal key, Long organisationId) {
        Organisation organisation = em.find(Organisation.class, organisationId);
        key.assertHasPermission(organisation, Permission.NODE_VIEW);
        return organisation;
    }

    public Organisation createOrganisation(KeyLocal key, Organisation organisation) {
        key.assertHasPermission(organisation.getParentNode(), Permission.ORGANISATION_CREATE);
        ChangeDelta changeDelta = organisation.addChangeDelta(ChangeDeltaType.CREATE, key.getUser());
        contactableBean.logCreate(organisation, changeDelta);
        em.persist(organisation);
        em.persist(changeDelta);
        return organisation;
    }

    public void editOrganisation(KeyLocal key, Organisation organisation) {
        Organisation current = em.find(Organisation.class, organisation.getId());
        key.assertHasPermission(organisation, Permission.ORGANISATION_EDIT);
        ChangeDelta changeDelta = organisation.addChangeDelta(ChangeDeltaType.EDIT, key.getUser());
        contactableBean.logEdit(organisation, current, changeDelta);
        em.persist(changeDelta);
        em.merge(organisation);
    }


    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method" or "Web Service > Add Operation")
 
}
